#!/usr/bin/env bash
#-------------------------------------------------------
#	FileName	: isr.sh
#	Author		：hpy
#	Date		：2025年06月24日
#	Description	：用于修正MCL51的中断向量表
#-------------------------------------------------------
ISR_STRT_ADDR=32
DST_DIR=$1 

MAP_FILE=build/firmware.map
HEX_FILE=build/firmware.hex

IT_FILE=$(find $DST_DIR -type f -name "it.h")

echo "find it.h file: $IT_FILE"
test -z "$IT_FILE" && echo "it.h file not found" && exit 0

ISR_SRC=$(cat $IT_FILE | grep "^INT_REGISTER" | xargs )
echo "ISR_SRC: $ISR_SRC"


for i in $ISR_SRC
do
    # 匹配中断注册实际内容
    if [[ $i != *"INT_REGISTER"* ]]; then
        continue
    fi

    str=${i#*(}  # 去除从开头到第一个 ( 的部分
    result=${str%%,*}  # 去除从第一个 , 到结尾的部分

    test -z "$result" && continue
    # echo "result: $result"

    isr_entry_point=$((ISR_STRT_ADDR+result*2))
    
    isr_fun_name="_isr${result}"
    # echo "$isr_fun_name: $isr_entry_point"

    ISR_FUNC_ADDR=$(cat $MAP_FILE | grep -w $isr_fun_name | awk '{print $2}')
    # 打印ISR_FUNC_ADDR的长度 
    test 0 -eq ${#ISR_FUNC_ADDR} && echo "$i is no isr function (void isr$result(void))" && exit 1

    # ISR_FUNC_ADDR 为十六进制数据，拆分为低8bit和高8bit
    ISR_FUNC_ADDR_LOW=${ISR_FUNC_ADDR:6:2}
    ISR_FUNC_ADDR_HIGH=${ISR_FUNC_ADDR:4:2}
    
    # 替换 firmware.hex 指定行的内容
    line1=$((isr_entry_point+1))
    line2=$((isr_entry_point+2))
    sed -i "${line1}s/.*/${ISR_FUNC_ADDR_HIGH}/" $HEX_FILE
    sed -i "${line2}s/.*/${ISR_FUNC_ADDR_LOW}/" $HEX_FILE
done
